//
//  UIImageView+click.m
//  dataGathering
//
//  Created by apple on 15/1/8.
//  Copyright (c) 2015年 shuili. All rights reserved.
//

#import "UIImageView+click.h"

@implementation UIImageView (click)
@dynamic canClick;

CGRect defaultFrame;
id dImageView;
- (void)canClickIt:(BOOL)click {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapIt:)];
    [tap setNumberOfTapsRequired:1];
    self.userInteractionEnabled = YES;
    [self addGestureRecognizer:tap];
}

- (void)tapIt:(UIGestureRecognizer*)sender {
    [UIImageView showImage:(UIImageView*)sender.view];
}
+ (void)showImage:(UIImageView *)defaultImageView{
    UIImage *image = defaultImageView.image;
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIView *backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    defaultFrame = [defaultImageView convertRect:defaultImageView.bounds toView:window];//关键代码，坐标系转换
    backgroundView.backgroundColor=[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    backgroundView.alpha = 0;
    dImageView = defaultImageView;
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:defaultFrame];
    imageView.image = image;
    imageView.tag = 1;
    [backgroundView addSubview:imageView];
    [window addSubview:backgroundView];
    
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
    [backgroundView addGestureRecognizer:tap];
    
    [UIView animateWithDuration:0.5 animations:^{
        defaultImageView.alpha = 0;
        imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
        backgroundView.alpha=1;
    } completion:^(BOOL finished) {
    }];
}

+ (void)hideImage:(UITapGestureRecognizer*)tap{
    UIView *backgroundView = tap.view;
    UIImageView *imageView = (UIImageView*)[tap.view viewWithTag:1];
    [UIView animateWithDuration:0.3 animations:^{
        imageView.frame = defaultFrame;
        backgroundView.alpha = 0;
    } completion:^(BOOL finished) {
        ((UIImageView*)dImageView).alpha = 1;
        [backgroundView removeFromSuperview];
    }];
}

@end
